package de.szut.sudoku.gui;

import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JFrame;

import de.szut.sudoku.main.GameController;

/**
 * Class that is used to control the user exiting the program
 * 
 * @author dqi12huisinga
 * 
 */
public class ExitOperator {
	/**
	 * Calls an exit operation
	 */
	public void callExitOperation() {
		// saves the current difficulty
		GameController
				.getInstance()
				.getConfiguration()
				.setProperty(
						"game.difficulty",
						GameController.getInstance().getdContainer()
								.getCurrentDifficulty().getDifficultyName());
		// saves the current language
		GameController
				.getInstance()
				.getConfiguration()
				.setProperty(
						"game.language",
						MainFrame.getInstance().getlContainer()
								.getCurrentLanguage());
		// saves the values
		try {
			GameController
					.getInstance()
					.getConfiguration()
					.store(new FileOutputStream(GameController.getInstance()
							.getConfigPath()), null);
		} catch (IOException e) {
			System.out.println("Config wasn't found!");
		}

		// asks the user to save the field with a JFileChooser
		if (MainFrame.getInstance().getSudokuPanel().isGameHasStarted()) {
			JFileChooser fileChooser = new JFileChooser();
			int option = fileChooser.showSaveDialog(null);
			if (option == JFileChooser.APPROVE_OPTION) {
				GameController
						.getInstance()
						.getGame()
						.saveFields(
								fileChooser.getSelectedFile().getAbsolutePath());
			}
		}

		MainFrame.getInstance().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}
